<?php
defined('APP_PATH') or die ('Unauthorized access');
/**
 * session处理核心库
 */
include_once(LIB_PATH.'/Db.php');
ini_set("session.save_handler","user");

final class Session
{
	private $save_handler = NULL;
	private $config = NULL;
	static private $_instance = NULL;
	
	private function __construct()
	{
		global $config;
		if(isset($config['session']) && $config['session']['save_handler'] == 'database'){
			$this->config = $config['session'];
			$this->save_handler = Db::getInstance();
			session_set_save_handler(
				array(&$this,"open"), 
				array(&$this,"close"), 
				array(&$this,"read"),
				array(&$this,"write"),
				array(&$this,"destroy"),
				array(&$this,"gc")
			);
			session_start();
		}
	}
	
	private function __clone()
	{
		
	}
	
	static public function getInstance()
	{
		if(is_null(self::$_instance) || !isset(self::$_instance)){
			self::$_instance = new Session();
		}
		return self::$_instance;
	}
	
	public function open($save_path, $session_name)
	{
		return true;
	}
	
	public function close()
	{
		$this->save_handler->close();
		return true;
	}
	
	public function write($id,$data)
	{
		$this->save_handler -> Config(array('table' => $this->config['save_table']));
		$where = array(array($this->config['save_pre'],'=',$id),array($this->config['save_colum_expiry'],'>',time()));
		$check = $this->save_handler->nums($where);
		if($check > 0){
			$arr = array(
				$this->config['save_colum_data'] => $data,
				$this->config['save_colum_expiry'] => time() + $this->config['save_lifetime']
			);
			$update = $this->save_handler->update($arr,$where);
			return $update ? true : false;
		}else{
			$arr = array(
				$this->config['save_pre'] => $id,
				$this->config['save_colum_data'] => $data,
				$this->config['save_colum_expiry'] => time() + $this->config['save_lifetime'],
				$this->config['save_colum_lifetime'] => $this->config['save_lifetime']
			);
			$insert = $this->save_handler->insert($arr);
			return $insert ? true : false;
		}
		
	}
	
	public function read($id)
	{
		$this->save_handler -> Config(array('table' => $this->config['save_table']));
		$where = array(array($this->config['save_pre'],'=',$id));
		$result = $this->save_handler->find($where);
		return $result[$this->config['save_colum_data']];
	}
	
	public function gc($maxlifetime)
	{
		$this->save_handler -> Config(array('table' => $this->config['save_table']));
		$where = array(array($this->config['save_colum_expiry'],'<',time()));
		$delete = $this->save_handler->delete($where);
		return $delete ? true : false;
	}
	
	public function destroy($id)
	{
		$this->save_handler -> Config(array('table' => $this->config['save_table']));
		$where = array(array($this->config['save_pre'],'=',$id));
		$delete = $this->save_handler->delete($where);
		return $delete ? true : false;
	}
	
}

Session::getInstance();


